package org.abacus.platform.data;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

class FetchResultSet implements Store {
	private final ResultSet rs;
	private int columnCount;
	private ResultSetMetaData metaData;
	private List<Map<String, Object>> store = new ArrayList<Map<String, Object>>();
	private List<String> keys;
	private List<Key> keysAlias;
	private static final String PREFIX = "c";

	public FetchResultSet(ResultSet rs) {
		super();
		this.rs = rs;
		try {
			this.metaData = rs.getMetaData();
			this.columnCount = this.metaData.getColumnCount();
			this.keys = new ArrayList<String>();
			this.keysAlias = new ArrayList<Key>();
			KeyBean k;
			String columnClassName;
			String columnLabel;
			for (int i = 1; i <= columnCount; i++) {
				this.keys.add(this.metaData.getColumnName(i).toLowerCase());
				k = new KeyBean();
				columnLabel = this.metaData.getColumnLabel(i);
				k.setLabel(columnLabel);
				columnClassName = this.metaData.getColumnClassName(i);
				columnClassName = columnClassName.substring(columnClassName.lastIndexOf(".") + 1).toLowerCase();
				k.setType(columnClassName);
				k.setKey(PREFIX + (i - 1));
				this.keysAlias.add(k);
			}
			getRows();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			close();
		}
	}

	private void getRows() throws SQLException {
		while (rs.next()) {
			store.add(getRows(rs));
		}
	}

	private Map<String, Object> getRows(ResultSet rs) throws SQLException {
		Map<String, Object> rows = new LinkedHashMap<String, Object>();
		for (int i = 1; i <= columnCount; i++) {
			rows.put(PREFIX + (i - 1), this.rs.getObject(i));
		}
		return rows;
	}

	@Override
	public List<Map<String, Object>> getStore() {
		return store;
	}

	@Override
	public void open() {

	}

	@Override
	public void close() {
		try {
			if (null != rs)
				rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	public List<Key> getKeys() {
		return keysAlias;
	}
}
